package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.CategoryService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping()
    public Result<Object> addCategory(@RequestBody JSONObject obj) {
        if (categoryService.addCategory(obj)){
            return Result.success();
        } else {
            return Result.error(CATEGORY_ADD_EXCEPTION_CODE, CATEGORY_ADD_EXCEPTION_MESSAGE);
        }
    }

    @GetMapping("/tree")
    public Result<JSONObject> getCategoryTree() {
        JSONObject categoryTree = categoryService.getCategoryTree();
        return Result.success(categoryTree);
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getCategoryList(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(categoryService.getCategoryList(pageNum, pageSize, condition));
    }

    @PutMapping()
    public Result<Object> updateCategory(@RequestBody JSONObject obj) {
        if (categoryService.updateCategory(obj)){
            return Result.success();
        } else {
            return Result.error(CATEGORY_UPDATE_EXCEPTION_CODE, CATEGORY_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @DeleteMapping("/{id}")
    public Result<Object> deleteCategory(@PathVariable("id") Integer id) {
        if (categoryService.deleteCategory(id)) {
            return Result.success();
        } else {
            return Result.error(CATEGORY_DELETE_EXCEPTION_CODE, CATEGORY_DELETE_EXCEPTION_MESSAGE);
        }
    }
}
